package cn.practice.articlepractice.controller;

import cn.practice.articlepractice.common.response.JsonResult;
import cn.practice.articlepractice.common.response.StatusCode;
import cn.practice.articlepractice.pojo.dto.UserArticleDTO;
import cn.practice.articlepractice.pojo.dto.UserLoginDTO;
import cn.practice.articlepractice.pojo.entity.Article;
import cn.practice.articlepractice.pojo.mapper.UserMapper;
import cn.practice.articlepractice.pojo.vo.ArticleVO;
import cn.practice.articlepractice.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@Slf4j
@RestController
@Api(tags = "用户模块")
@RequestMapping("/v1/users/")
@Validated
public class UserController {
    // 自动装配
    @Autowired
    private UserMapper userMapper;

    // 用户登录
    @PostMapping("login")
    @ApiOperation(value = "用户登录")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
        // 登录方法
        log.debug("userLoginDTO:" + userLoginDTO);
        UserVO uservo = userMapper.userLogin(userLoginDTO);
        if (uservo == null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }

        // 存入会话
        session.setAttribute("user", uservo);

        return JsonResult.success();
    }

    // 发表文章
    @PostMapping("article")
    @ApiOperation(value = "发表文章")
    public JsonResult article(@RequestBody @Validated UserArticleDTO userArticleDTO, @ApiIgnore HttpSession session){
        //
        log.debug("userArticleDTO:" + userArticleDTO);
        // 通过会话判断用户是否登录
        UserVO uservo = (UserVO) session.getAttribute("user");
        if (uservo == null){
            return new JsonResult(StatusCode.NOT_LOGIN);
        }


        Article article = new Article();
        BeanUtils.copyProperties(userArticleDTO, article);
        article.setUserId(uservo.getId());

        userMapper.article(article);
        return JsonResult.success();
    }

    // 通过id获取文章
    @GetMapping("selectByArticleId")
    @ApiOperation(value = "通过id获取文章")
    public JsonResult selectByArticleId(@RequestParam
                                            @Range(min = 1,max = 200, message = "id必须在1到200之间")
                                            Long id){
        ArticleVO articlevo = userMapper.selectByArticleId(id);
        return JsonResult.success(articlevo);
    }
}
